#!/usr/bin/env php
<?php
date_default_timezone_set('Asia/Shanghai');

define('ROOT_PATH',__DIR__);
define('CONFIG_PATH',ROOT_PATH.'/config');
define('RUN_TIME_PATH',ROOT_PATH.'/runtime');
define('CACHE_PATH',RUN_TIME_PATH.'/cache');
define('LOG_PATH',RUN_TIME_PATH.'/log');
define('WEB_PATH',ROOT_PATH.'/web');
define('VIEWS_PATH',ROOT_PATH.'/views');

require './vendor/autoload.php';

use Swoole\Process;
use Swoole\Runtime;
use app\service\HttpServer;

if(!is_dir(RUN_TIME_PATH)){
    mkdir(RUN_TIME_PATH,0755);
}
if(!is_writable(RUN_TIME_PATH)){
    print_ln(RUN_TIME_PATH.' is not writable.');
    exit();
}
if(!is_dir(LOG_PATH)){
    mkdir(LOG_PATH,0755);
}
if(!is_dir(CACHE_PATH)){
    mkdir(CACHE_PATH,0755);
}

$command = $argv[1]??'';
switch ($command){
    case 'start':
        run(($argv[2]??'') == '-d');
        break;
    case 'stop':
        stop();
        break;
    default:
        print_error("use `php {$argv[0]} start|start -d|stop`");
        exit();
}

/**
 * run
 * @param bool $daemonize
 */
function run(bool $daemonize=false)
{
    Runtime::enableCoroutine(SWOOLE_HOOK_ALL);
    (new HttpServer($daemonize))->start();
}

function stop()
{
    if(!empty($pid = file_get_contents(RUN_TIME_PATH.'/httpServer.pid'))){
        if(!Process::kill($pid,0)){
            print_error("server is not running.");
        }else{
            if (!Process::kill($pid, 9)) {
                print_error("stop server fail:pid({$pid}) not exist.");
            }else{
                print_success("stop server success.");
            }
        }
    }else{
        print_error("stop server fail:pid file does not exist");
    }

}